﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;

namespace Eamon.MeituanDotnetSDK.utils
{
    public class EncryptUtil
    {
        public EncryptUtil()
        {
        }
        //public static string GenerateSign(GenerateSignRequest request)
        //{
        //    if (request.SignMethod!=@enum.SignMethodEnum.SHA1)
        //    {
        //        return "";
        //    }
        //    List<string> array = new List<string>();
        //    foreach (var item in request.Parameters)
        //    {
        //        array.Add(item.Key);
        //    }
        //    array.Sort();
        //    StringBuilder stringBuilder = new StringBuilder();
        //    stringBuilder.Append(request.AppSecret);
        //    foreach (var key in array)
        //    {
        //        stringBuilder.Append(key).Append(request.Parameters[key]);
        //    }
        //    stringBuilder.Append(request.AppSecret);
        //    return GenMd5(stringBuilder.ToString());
        //}

        //[Obsolete]
        //public static string GenMd5(string info)
        //{

        //    byte[] byteUserPwd = Encoding.UTF8.GetBytes(info);

        //    MD5CryptoServiceProvider myMd5 = new MD5CryptoServiceProvider();

        //    byte[] byteMd5UserPwd = myMd5.ComputeHash(byteUserPwd);

        //    return ByteArrayToHex(byteMd5UserPwd);

        //}

        //public static string ByteArrayToHex(byte[] bytes)
        //{
        //    string returnStr = "";
        //    if (bytes != null)
        //    {
        //        for (int i = 0; i < bytes.Length; i++)
        //        {
        //            returnStr += bytes[i].ToString("x2");
        //        }
        //    }
        //    return returnStr;
        //}

        /// <summary>
        /// https://developer.meituan.com/docs/biz/comm-dev-isv-sign-rule
        /// </summary>
        /// <param name="signKey"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public static string getSign(string signKey, Hashtable param)
        {
            ArrayList keys = new ArrayList(param.Keys);
            keys.Sort(); //按字母顺序进行排序
            string resultStr = "";
            foreach (string key in keys)
            {
                string value = param[key].ToString();
                if (key != "sign" && value != null && value != "")
                {
                    resultStr = resultStr + key + value;
                }
            }
            resultStr = signKey + resultStr;
            SHA1 sha1 = new SHA1CryptoServiceProvider();
            byte[] rstRes = sha1.ComputeHash(Encoding.UTF8.GetBytes(resultStr));
            string hex = BitConverter.ToString(rstRes, 0).Replace("-", string.Empty).ToLower();

            return hex;
        }
    }
}
